package com.wangyukai.jmonitor.plugin;

import com.wangyukai.jmonitor.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class LdzhTomcatPlugin implements IMonitorPlugin{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String executeCheck() {
//        String loginurl = ServerConfig.getConfigValue("ldzh.login.url");
        String loginurl = "";
        try {
            StringBuilder result = sendGetRequest(loginurl);

            if(result.indexOf("<body ng-controller=\"indexController\">") >= 0){
                return "登录成功，并成功访问首页";
            }
            logger.error("返回错误数据:\r\n" + result.toString());
            return "登录失败，返回数据错误.详情查看日志";
        }catch (Exception ex){
            return "登录失败，" + ex.getMessage();
        }


    }

    /**
     * 根据参数发送GET请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    private StringBuilder sendGetRequest(String url) throws IOException {
        StringBuilder result = new StringBuilder();
        URL realUrl = new URL(url);
        HttpURLConnection urlConn = null;
        BufferedReader in = null;
        try{
            urlConn = (HttpURLConnection) realUrl.openConnection();
            urlConn.setConnectTimeout(30000);
            urlConn.setReadTimeout(30000);
            urlConn.setRequestProperty("accept", "*/*");
            urlConn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            urlConn.connect();
            // 用Buffer流来读取响应
            in = new BufferedReader(new InputStreamReader(
                    urlConn.getInputStream(), "UTF-8"));
            String line;

            while ((line = in.readLine()) != null) {
                result.append(line);
            }

        } finally {
            if(null != in){
                in.close();
            }
            if(null != urlConn){
                urlConn.disconnect();
            }

        }

        return result;
    }
}
